from django.db import models
import datetime
import xml.dom.minidom

# Create your models here.
class Day(models.Model):
    date = models.DateField(blank=True, default=str(datetime.date.today()))
    def __unicode__(self):
        return self.date

class Task(models.Model):
    name = models.CharField(max_length=100)
    xml_config_file_dest = lambda s, f: "tasks/%s/%s" % (s.name, f)
    xml_config_file = models.FileField(blank=True, max_length=400, upload_to=xml_config_file_dest,
        verbose_name='XML config file' )

    def get_table_params(self, param, incl_types=False):
        """ Get a specific type of Task parameter from the XML file

        param : string
            ex: 'TLComponent', 'TargetComponent', etc.
        incl_types : boolean, opt, 
            return datatype along with param name if true
        """
        doc = xml.dom.minidom.parse( open(path.join(settings.MEDIA_ROOT, self.xml_config_file.name)) ) 
        config = doc.getElementsByTagName('Config')[0]
        table_params = [ (c.getAttribute('name'), c.getAttribute('type')) for c in config.getElementsByTagName(param)]
        if incl_types:
            return table_params
        else:
            return [x[0] for x in table_params]

class TaskParams(models.Model):
    task = models.ForeignKey(Task)
    name = models.CharField(max_length=100, blank=True)
    comments = models.TextField(blank=True)
    def param_file_dest(self, f):
        if not self.name == '':
            return "tasks/%s/%s" % (self.task.name, self.name+'.dtp')#path.basename(f))
        else:
            return "tasks/%s/%s" % (self.task.name, f)
    param_file = models.FileField(blank=True, max_length=400, upload_to=param_file_dest )
    
    
class Block(models.Model):
    name = models.CharField(max_length=15)
    day = models.ForeignKey(Day)
    task = models.ForeignKey(Task, blank=True)
    task_params = models.ForeignKey(TaskParams)
